package servlet;

import com.fasterxml.jackson.databind.ObjectMapper;
import dao.MusicDao;
import entity.Music;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

@WebServlet("/deleteServlet")
//根据id删除音乐
public class DeleteMusicServlet extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("utf-8");
        resp.setContentType("application/json; charset=utf-8");
        String sId = req.getParameter("id");
        int id = Integer.parseInt(sId);
        MusicDao musicDao = new MusicDao();
        Music music = musicDao.findMusicById(id);
        Map<String,Object> return_map = new HashMap<>();
        if (music == null){
            return;
        }
        //有当前需要删除的音乐
        int ret = musicDao.deleteMusicById(id);
        System.out.println("ret:"+ret);
        if (ret == 1){
            //数据库删除成功，服务器上的数据也需要发生改变
            //删除服务器目录下的对应的文件
            File file = new File("D:\\项目\\music\\src" +
                    "\\main\\webapp\\"+music.getUrl()+".mp3");
            //删除格式不同，后缀要做相应改变.mp3,.docx等
            if (file.delete()){
                return_map.put("msg",true);
                System.out.println("true");
            }else {
                return_map.put("msg",false);
                System.out.println("false");
            }
        }else{
            return_map.put("msg",false);
        }
        ObjectMapper mapper = new ObjectMapper();
        //利用Jackson将map转化为json对象，
        // writer 将转换后的json字符串保存到字符输出流中，最后给客户端
        mapper.writeValue(resp.getWriter(),return_map);
    }
}
